﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Runtime.Serialization;

namespace Framework.Common.Serializer
{
    public class DataContractJsonSerializeHelper : SerializeBase<string>
    {
        #region dict
        private static Dictionary<Type, DataContractJsonSerializer> dict = new Dictionary<Type, DataContractJsonSerializer>();

        public static DataContractJsonSerializer GetSerializer(Type t)
        {
            DataContractJsonSerializer serializer;
            if (!dict.TryGetValue(t, out serializer))
            {
                serializer = new DataContractJsonSerializer(t);
                dict[t] = serializer;
            }
            return serializer;
        }
        #endregion


        public override string Serialize(object obj)
        {
            if (obj != null)
            {
                DataContractJsonSerializer serializer = GetSerializer(obj.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    return Encoding.UTF8.GetString(ms.GetBuffer());
                }
            }
            return string.Empty;
        }

        public override T DeSerialize<T>(string source)
        {
            if (!string.IsNullOrWhiteSpace(source))
            {
                DataContractJsonSerializer serializer = GetSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(source)))
                {
                    T jto = (T)serializer.ReadObject(ms);
                    return jto;
                }
            }
            return default(T);
        }

        public override bool SerializeToFile(object obj, string fullPath)
        {
            if (obj != null)
            {
                DataContractJsonSerializer serializer = GetSerializer(obj.GetType());
                return base.SerializeToFile(obj, fullPath, (stream) => serializer.WriteObject(stream, obj));
            }
            return false;
        }

        public override T DeSerializeFromFile<T>(string fullPath)
        {
            DataContractJsonSerializer serializer = GetSerializer(typeof(T));
            return base.DeSerializeFromFile<T>(fullPath, (stream) => serializer.ReadObject(stream));
        }
    }
}
